﻿namespace S7.Net.Types
{
    using System;

    public static class Int
    {
        public static short CWord(int value)
        {
            if (value > 0x7fff)
            {
                value -= 0x8000;
                value = 0x8000 - value;
                value *= -1;
            }
            return (short) value;
        }

        public static short FromByteArray(byte[] bytes)
        {
            return FromBytes(bytes[1], bytes[0]);
        }

        public static short FromBytes(byte LoVal, byte HiVal)
        {
            return (short) ((HiVal * 0x100) + LoVal);
        }

        public static short[] ToArray(byte[] bytes)
        {
            short[] numArray = new short[bytes.Length / 2];
            int num = 0;
            for (int i = 0; i < (bytes.Length / 2); i++)
            {
                numArray[i] = FromByteArray(new byte[] { bytes[num++], bytes[num++] });
            }
            return numArray;
        }

        public static byte[] ToByteArray(short value)
        {
            byte[] buffer = new byte[2];
            int num = 2;
            long num2 = value;
            for (int i = 0; i < num; i++)
            {
                long num4 = (long) Math.Pow(256.0, (double) i);
                long num5 = num2 / num4;
                buffer[(num - i) - 1] = (byte) (num5 & 0xffL);
                num2 -= buffer[(num - i) - 1] * num4;
            }
            return buffer;
        }

        public static byte[] ToByteArray(short[] value)
        {
            ByteArray array = new ByteArray();
            foreach (short num in value)
            {
                array.Add(ToByteArray(num));
            }
            return array.array;
        }
    }
}

